package com.photographysharing.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.photographysharing.common.ThreadLocalOperation;
import com.photographysharing.dto.UserWatchPhotoDTO;
import com.photographysharing.entity.UserWatchPhotos;
import com.photographysharing.exception.ServiceException;
import com.photographysharing.response.DatasResponse;
import com.photographysharing.service.StatisticsService;
import com.photographysharing.service.UserWatchPhotosService;
import com.photographysharing.util.JWTUtil;
import com.photographysharing.util.RedisHelp;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/userwatch")
public class UserWatchController {

    private StatisticsService statisticsService;
    private UserWatchPhotosService userWatchService;
    private RedisHelp redisHelp;

    public UserWatchController(StatisticsService statisticsService, UserWatchPhotosService userWatchService, RedisHelp redisHelp) {
        this.statisticsService = statisticsService;
        this.userWatchService = userWatchService;
        this.redisHelp = redisHelp;
    }


    @GetMapping("/watch")
    public void watch(String photoId){
        String userId = ThreadLocalOperation.getThreadLocalUserId();
        //先查询是否在库，避免数据过多
        QueryWrapper<UserWatchPhotos> qw = new QueryWrapper<>();
        qw.eq("user_id",userId);
        qw.eq("photo_id",photoId);
        UserWatchPhotos userWatchPhotos = userWatchService.getOne(qw);
        if(userWatchPhotos ==null){
            userWatchPhotos = new UserWatchPhotos(userId,photoId);
            //入库
            userWatchService.save(userWatchPhotos);

        }
        //每个用户一分钟增加一次观看统计
        String json = redisHelp.getString("watch"+userId+photoId);
        if(json == null){
            statisticsService.increaseWatch(photoId);
            redisHelp.setString("watch"+userId+photoId,"1",1);
        }
    }


    @GetMapping("/selectByMyself")
    public DatasResponse<UserWatchPhotoDTO> selectByMyself(){
        return userWatchService.selectByMyself();
    }
}



























